// ==UserScript==
// @name         京东抢购-详情页
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  京东商品抢购-详情页
// @author       twisly
// @match        *://*/*
// @icon         
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

(function () {
    'use strict';
    // 获取当前页面url
    var currPageUrl = window.location.href;

    // 详情页
    if (currPageUrl.indexOf("product") > 0) {
        var detailPageJob = setInterval(function () {
            if (document.querySelectorAll('.process_desc_item')[1] != null) {
                window.clearInterval(detailPageJob);
                // 商品ID
                let goodsId = currPageUrl.substring(currPageUrl.lastIndexOf('/') + 1, currPageUrl.lastIndexOf('.html'));
                // 开始购买时间
                let buyTime = document.querySelectorAll('.process_desc_item')[1].innerHTML.split(' 至 ')[1];
                GM_setValue('jd_seckill_buy_time', buyTime);
                console.info("商品ID: %s, 开始购买时间: %s", goodsId, buyTime)

                // 跳转订单页面
                window.location.href = 'https://p.m.jd.com/norder/order.action?wareNum=1&wareId=' + goodsId;
            }
        }, 200);
    }

    // 订单页面
    if (currPageUrl.indexOf('confirm.shtml') > 0) {
        var buyTime = GM_getValue('jd_seckill_buy_time', null);
        var now = new Date();
        var year = now.getFullYear(),
            month = now.getMonth() + 1,
            day = now.getDate();
        if (month < 10) {
            month = "0" + month
        }
        if (day < 10) {
            day = "0" + day
        }
        buyTime = year + "-" + month + "-" + day + ' ' + buyTime + ':00';
        var buyTs = new Date(buyTime).getTime();
        var confirmOrderJob = window.setInterval(function () {
            console.info("开始购买时间: %s", buyTime)
            let nowTs = new Date().getTime();
            if (nowTs - buyTs >= 0) {
                window.clearInterval(confirmOrderJob);
                document.querySelector('.Submit_submit_kaKYK').click()
            }
        }, 10);
    }

    // 支付页面
    if (currPageUrl.indexOf('mpay') > 0) {
        document.querySelector('.payBtn > span').click()
    }
})();